import { Button, Form, Input, Modal } from 'antd';
import axios from 'axios';
import React from 'react';
import { Link, useNavigate } from 'react-router-dom'
import { LoginRouter } from '../../api';

const Login = () => {
  const navigate = useNavigate();

  React.useEffect(() => {
    if (localStorage.getItem('login-user')) {
      navigate(`/home`)
    }
  }, [])//eslint-disable-line

  const onFinish = (values) => {
    // console.log(values);
    axios({
      url: LoginRouter,
      method: 'post',
      data: values
    }).then(res => {
      if (res.data.message === '登录成功') {
        localStorage.setItem('login-user', res.data.account)
        localStorage.setItem('user-avatar', res.data.avatar)
        navigate('/home', {
          state: {
            u_acc: res.data.account
          }
        })
      }
      else {
        (() => {
          Modal.error({
            title: '错误',
            content: res.data.message,
          });
        })()
      }

      // console.log(res.data.message);
      // sessionStorage.setItem( 'token' , res.data.token);
      // return res.data.message
    })
    // console.log('Success:', values);
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <div className="loginContainer">
      <Form
        className='loginform'
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 8,
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="on"
      >
        <Form.Item
          label="Account"
          name="account"
          rules={[
            {
              required: true,
              message: '输入账号',
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Password"
          name="password"
          rules={[
            {
              required: true,
              message: '输入密码!',
            },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          wrapperCol={{
            span: 8
          }}
        >
          <Button type="primary" htmlType="submit" block>
            登录
          </Button>
        </Form.Item>
        <Form.Item
          wrapperCol={{

            span: 8
          }}
        >
          <Link to='/register'>
            <Button type="primary" block>
              注册
            </Button> 
          </Link>

        </Form.Item>

      </Form>
    </div>
  );
};

export default Login;